'use client'

import { useState, useEffect } from 'react'
import { MoreHorizontal, PlusCircle } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useToast } from '@/components/ui/use-toast'
import RouterHook from '@/components/RouterHook'
import Loading from '@/components/Loading'
import useRequest from '@/utils/request'
import common from '@/utils/common'
import PayDialog from '@/components/PayDialog'

export default function Projects() {
  const [loading, setLoading] = useState(true)
  const [projects, setProjects] = useState([])
  const [paginationConfig, setPaginationConfig] = useState({
    total: 0,
    per_page: 0,
    current_page: 0,
    last_page: 0,
  })
  const { toast } = useToast()
  const request = useRequest()

  const fetchData = async () => {
    try {
      const res = await request.get('red_growth/project')
      setLoading(false)
      setProjects(res.data.data)
      setPaginationConfig({
        total: res.data.total,
        perPage: res.data.per_page,
        currentPage: res.data.current_page,
        lastPage: res.data.last_page,
      })

      window.gtag && window.gtag('event', 'conversion', { send_to: 'AW-16493707962/NWTyCMu63MYZELqF6Lg9' })
    } catch (error) {}
  }

  const delData = async data => {
    const res = await request.delete(`red_growth/project?id=${data.id}`)
    toast({
      title: `Project '${data.brand}' has been deleted.`,
    })
    fetchData()
  }

  useEffect(() => {
    fetchData()
  }, [])

  if (loading) {
    return <Loading />
  }

  if (projects.length <= 0) {
    return (
      <div
        className="flex flex-1 items-center justify-center rounded-lg border border-dashed shadow-sm h-[500px] bg-card"
        x-chunk="dashboard-02-chunk-1"
      >
        <div className="flex flex-col items-center gap-1 text-center">
          <h3 className="text-2xl font-bold tracking-tight">Create your first project</h3>
          <p className="text-sm text-muted-foreground">To find your customers only 2 minutes</p>
          <RouterHook path="/projects/add">
            <Button className="mt-4">Add Project</Button>
          </RouterHook>
        </div>
      </div>
    )
  } else {
    return (
      <>
        <div className="flex items-center">
          <div className="mr-auto flex items-center gap-2">
            <RouterHook path="/projects/add">
              <Button size="sm" className="h-8 gap-1">
                <PlusCircle className="h-3.5 w-3.5" />
                <span className="whitespace-nowrap">Add Project</span>
              </Button>
            </RouterHook>
          </div>
        </div>
        <Card x-chunk="dashboard-06-chunk-0">
          <CardHeader>
            <CardTitle>Projects</CardTitle>
            <CardDescription>
              Your current projects are listed below. You will receive an email whenever these are found (usually within
              a few minutes).
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Brand</TableHead>
                  <TableHead>Enabled</TableHead>
                  <TableHead className="hidden md:table-cell">Hits last 24h</TableHead>
                  <TableHead className="hidden md:table-cell">Created at</TableHead>
                  <TableHead>
                    <span className="sr-only">Actions</span>
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {projects.map(project => {
                  return (
                    <TableRow key={project.id}>
                      <TableCell className="font-medium">{project.brand}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{project.status === '2' ? 'Active' : 'Draft'}</Badge>
                      </TableCell>
                      <TableCell className="hidden md:table-cell">{project.hits_24h}</TableCell>
                      <TableCell className="hidden md:table-cell">
                        {common.formatUnixTimestamp(project.createtime)}
                      </TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button aria-haspopup="true" size="icon" variant="ghost">
                              <MoreHorizontal className="h-4 w-4" />
                              <span className="sr-only">Toggle menu</span>
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuLabel>Actions</DropdownMenuLabel>
                            <RouterHook path={`/projects/edit/${project.id}`}>
                              <DropdownMenuItem>Edit</DropdownMenuItem>
                            </RouterHook>
                            <DropdownMenuItem
                              onClick={() => {
                                delData(project)
                              }}
                            >
                              Delete
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardContent>
          <CardFooter>
            <div className="text-xs text-muted-foreground">
              Showing <strong>1-15</strong> of <strong>{paginationConfig.total}</strong> projects
            </div>
          </CardFooter>
        </Card>
        <PayDialog />
      </>
    )
  }
}
